﻿using AbpApplication.InPut;
using Azure;
using CommunityToolkit.Mvvm.Input;
using HandyControl.Controls;
using Microsoft.AspNetCore.SignalR.Client;
using NewWms.Apiservice;
using NewWms.Apiservice.Dto;
using NewWms.Apiservice.InPut;
using NewWms.Extend;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Reconstruct_Desktop.Apiservice.Dto;
using SingalR.Client;
using System.Collections;
using System.Windows;
using WcsZz.Extend;
using wms_wpf;
using wms_wpf.Apiservice;
using wms_wpf.Extend;
using wms_wpf.InPut;
using MessageBox = HandyControl.Controls.MessageBox;

namespace NewWms.ViewModels
{
    public partial class UpAndDownShelvesViewModel : BindableBase, INavigationAware
    {
        //define
        private readonly IBaseService baseService;
        private readonly IViewService viewService;
        private readonly IEssService essService;
        public UpAndDownShelvesViewModel()
        {
        
            baseService = new BaseService();
            viewService = new ViewService();
            essService = new EssService();
            InPut_BaseService7= new InPut_BaseService7();
            InPut_BaseService6=new InPut_BaseService6();
            InPut_BaseService4= new InPut_BaseService4();
            InPut_ViewService4 = new InPut_ViewService4();
            InPut_ViewService10 =new InPut_ViewService10();
            View_MaterialDtos = new List<View_MaterialDto>();
            View_TaskOrderDtos=new List<View_TaskOrderDto>();
            InlethouseModels = new List<InlethouseLineDto>();
           Command = new DelegateCommand<string>(Method);
         
            View_TaskOrder();
            GetInletCanves();
            GetHubConnectionAsync();
            EventAggregatorHelper.EventAggregator.ResgiterMessage(arg =>
            {
                CreateMaterialBase();
            }, "新增物料");
            EventAggregatorHelper.EventAggregator.ResgiterMessage(arg =>
            {
                DeleteMaterial();
            }, "删除物料");
            EventAggregatorHelper.EventAggregator.ResgiterMessage(arg =>
            {
                View_MaterialDto();
            }, "刷新页面");
        }
        private InPut_BaseService7 inPut_BaseService7;
        public InPut_BaseService7 InPut_BaseService7
        {
            get { return inPut_BaseService7; }
            set { inPut_BaseService7 = value;RaisePropertyChanged(); }
        }
        private InPut_BaseService6 inPut_BaseService6;
        public InPut_BaseService6 InPut_BaseService6
        {
            get { return inPut_BaseService6; }
            set { inPut_BaseService6 = value;RaisePropertyChanged();}
        }
        private InPut_ViewService10 inPut_ViewService10;
        public InPut_ViewService10 InPut_ViewService10
        {
            get { return inPut_ViewService10; }
            set { inPut_ViewService10 = value;RaisePropertyChanged(); }
        }
        private InPut_ViewService4 inPut_ViewService4;
        public InPut_ViewService4 InPut_ViewService4
        {
            get { return inPut_ViewService4; }
            set { inPut_ViewService4 = value;RaisePropertyChanged(); }
        }
        private List<View_MaterialDto> view_MaterialDtos;
        public List<View_MaterialDto> View_MaterialDtos
        {
            get { return view_MaterialDtos; }
            set { view_MaterialDtos = value; RaisePropertyChanged(); }
        }
        private List<View_TaskOrderDto> view_TaskOrderDtos;
        public List<View_TaskOrderDto> View_TaskOrderDtos
        {
            get { return view_TaskOrderDtos; }
            set { view_TaskOrderDtos = value;RaisePropertyChanged();}
        }
        private List<View_NeetOutMaterialDto> view_NeetOutMaterialDtos;
        public List<View_NeetOutMaterialDto> View_NeetOutMaterialDtos
        {
            get { return view_NeetOutMaterialDtos; }
            set { view_NeetOutMaterialDtos = value; RaisePropertyChanged(); }
        }


        private List<InlethouseLineDto> inlethouseModels;

        public List<InlethouseLineDto> InlethouseModels
        {
            get { return inlethouseModels; }
            set { inlethouseModels = value; RaisePropertyChanged(); }
        }

        private string materialcode;
        public string MaterialCode
        {
            get { return materialcode; }
            set { materialcode = value; RaisePropertyChanged(); }
        }
        private string boxcode;
        public string BoxCode
        {
            get { return boxcode; }
            set { boxcode = value; RaisePropertyChanged(); }
        }
        private string boxgridcode;
        public string BoxGridCode
        {
            get { return boxgridcode; }
            set { boxgridcode = value; RaisePropertyChanged(); }
        }
        private string quantity;
        public string Quantity
        {
            get { return quantity; }
            set { quantity = value;RaisePropertyChanged(); }
        }
        private string viewDelQuantity;
        public string ViewDelQuantity
        {
            get { return viewDelQuantity; }
            set { viewDelQuantity = value;RaisePropertyChanged(); }
        }
        private InPut_BaseService4 inPut_BaseService4;
        public InPut_BaseService4 InPut_BaseService4
        {
            get { return inPut_BaseService4; }
            set { inPut_BaseService4 = value;RaisePropertyChanged(); }
        }
        private bool _isSubmitting=true;
        public bool IsSubmitting 
        {
            get { return _isSubmitting; }
            set { _isSubmitting = value; RaisePropertyChanged(); }
        }
        public DelegateCommand<string> Command { get; set; }  

        //功能
        public void Method(string obj)
        {
            switch (obj)
            {
                case "CreateMaterialBase": CreateMaterialBase(); break;
                case "View_BoxGrid_Material": break;
                case "DeleteBoxs": break;
                case "CreateTaskOrder": CreateTaskOrder(); break;
                case "View_TaskOrder":
                    View_TaskOrder();break;
                case "DeleteMaterial":
                    DeleteMaterial();break;



            }
        }
        //新增物料
        private async void CreateMaterialBase()
        {
            InPut_BaseService7.MaterialCode= ExtendRandom.CreateRandom();
            MaterialCode = InPut_BaseService7.MaterialCode; 
                bool Nullres = InPut_BaseService7.GetType().GetProperties().All(property => property.GetValue(InPut_BaseService7) != null);
            if (!Nullres) { MessageBox.Info("请输入完整"); return; }
            BoxGridCode = await baseService.CreateMaterialBase(InPut_BaseService7);
            if (!string.IsNullOrEmpty(BoxGridCode))
            {
               
                await baseService.CreateLog("入库", "物料入箱了", null, InPut_BaseService7.MaterialCode, InPut_BaseService7.MaterialProertyName, null, InPut_BaseService7.Quantity.ToString(), null,  BoxGridCode, null);
                InPut_BaseService7.MaterialProertyName = "";
                InPut_BaseService7.Quantity=null;
            }           
            View_MaterialDto();
            if (!string.IsNullOrEmpty(BoxGridCode))
            {
                InPut_BaseService7.BoxCode = "";
            }

        }
        //更新数量
        [RelayCommand]
        private async  void UpdateMaterialBaserQuantity()
        {
            InPut_BaseService7.MaterialCode = ExtendRandom.CreateRandom();
            MaterialCode = InPut_BaseService7.MaterialCode;
            bool Nullres = InPut_BaseService7.GetType().GetProperties().All(property => property.GetValue(InPut_BaseService7) != null);
            if (!Nullres) { MessageBox.Info("请输入完整"); return; }
            bool res = await baseService.UpdateMaterialBaserQuantity(InPut_BaseService7);
            if (res)
            {
                await baseService.CreateLog("修改", $"物料修改了数量:{InPut_BaseService7.MaterialProertyName}:{InPut_BaseService7.Quantity}:{InPut_BaseService7.BoxCode}", null, null,null , null, InPut_BaseService7.Quantity.ToString(), null, BoxGridCode, null);
                InPut_BaseService7.MaterialProertyName = "";
                InPut_BaseService7.Quantity = null;
            }
            View_MaterialDto();
            if (res)
            {
                InPut_BaseService7.BoxCode = "";
            }
      
        }
        //新增Agv入库任务
        private async void CreateTaskOrder()
        {
            InPut_BaseService6.BoxCode = BoxCode;
            inPut_BaseService6.InletCode=GlobalVariable.OutletCode;
            bool Nullres = InPut_BaseService6.GetType().GetProperties().All(property => property.GetValue(InPut_BaseService6) != null);
            if (!Nullres) { MessageBox.Info("请检查箱号和入库口"); return; }
            Tuple<bool,string> CreateTaskOrder_tuple =  await baseService.CreateTaskOrder(InPut_BaseService6);
            if (CreateTaskOrder_tuple.Item1)
            {
                View_TaskOrder();
                GetInletCanves();
                //亮灯
                Ess_Input4 input4 = new Ess_Input4();
                input4.controllerCode=GlobalVariable.Machine;
                input4.index= "0002";
                input4.color = "WHITE";
                input4.mode = "LIGHT";
                input4.tagCode = CreateTaskOrder_tuple.Item2.Trim();
                input4.display = BoxCode.Substring(BoxCode.Length - 4);
                await essService.sendCommand(input4);
                BoxCode = "";
            }


        }
        //删除agv任务
        [RelayCommand]
        private async void DeleteTaskOrder(IList SelectItems)
        {
          
            List<string> InPut = new List<string>();
            foreach (View_TaskOrderDto item in SelectItems)
            {
                InPut.Add(item.TaskOrderCode);
            }
            bool res=   await baseService.DeleteTaskOrder(InPut);
            if (res) View_TaskOrder();
            GetInletCanves();


        }
        //取料确认
        private async void DeleteMaterial()
        {
            InPut_BaseService4.User=Jwt.UserName;
            bool Nullres = InPut_BaseService4.GetType().GetProperties().All(property => property.GetValue(InPut_BaseService4) != null);
            if (!Nullres) { MessageBox.Info("请输入完整"); return; }

          bool  res=  await baseService.DeleteMaterial(InPut_BaseService4);
            if (res)
            {
                ViewDelQuantity = InPut_BaseService4.MaterialProertyName +"-"+ InPut_BaseService4.DelQutity+ "个";
       //        await baseService.CreateLog("出库", $"物料被取走了", null, null, InPut_BaseService4.MaterialProertyName,
       //null, InPut_BaseService4.DelQutity, null, InPut_BaseService4.BoxCode, null);
                InPut_BaseService4.DelQutity = "";
                InPut_BaseService4.MaterialProertyName = "";
                InPut_BaseService4.BoxCode = "";
   
            }
            View_NeetOutMaterial();
        }
        //删物料
        [RelayCommand]
        private async void ReMovesMaterial(IList SelectItems)
        {
           MessageBoxResult messageBoxResult= HandyControl.Controls.MessageBox.Show("确认删除","提示",MessageBoxButton.YesNo);
            if (messageBoxResult != MessageBoxResult.Yes)
            {
                return;
            }
            List<string> InPut = new List<string>();
            foreach (View_MaterialDto item in SelectItems)
            {
                InPut.Add(item.MaterialCode);
            }
            bool res = await baseService.RemovesMaterial(InPut);
            if (res) View_MaterialDto();
        }
        //发送任务
        [RelayCommand]
        private async void TaskToEss(IList SelectItems)
        {
           
            try
            {
                IsSubmitting = false;
                foreach (View_TaskOrderDto item in SelectItems)
                {
                    bool Anyres= InlethouseModels.Any(x=>x.BoxCode == item.BoxCode);
                    if (!Anyres)
                    {
                        Growl.Warning("缓存货架上不存在"+item.BoxCode, "msg");
                        break;
                    }

                    if (item.State == "已下发") continue;
                    Ess_Input ess_Input = new Ess_Input();
                    ess_Input.taskType = "putaway";
                    ess_Input.taskGroupCode = "taskGroupCode-001";
                    ess_Input.groupPriority = item.groupPriority;
                    List<Tasks> data = new List<Tasks>();
                    Tasks ta = new Tasks();
                    ta.taskCode = item.TaskOrderCode;
                    ta.taskPriority = 0;
                    data.Add(ta);
                    ess_Input.tasks = data;
                    TaskDescribe td = new TaskDescribe();
                    td.containerCode = item.BoxCode;
                    td.containerType = "CT_KUBOT_STANDARD";
                    td.storageTag = "";
                    td.fromLocationCode = item.InlethouseCode;
                    td.toLocationCode = item.WarehouseCode;
                    td.toStationCode = "haiport_station_1";
                    td.isPutaway = false;
                    ta.taskDescribe = td;
                    string res = await essService.CreateTask(ess_Input);

                    if (res.Contains("OK"))
                    {
                        InPut_BaseService11 inPut = new InPut_BaseService11();
                        inPut.TaskOrderCode = item.TaskOrderCode;
                        inPut.Type = "已下发";
                        await baseService.UpdateTaskOrderState(inPut);
                        await baseService.CreateLog("上架", "发送了上架任务" + item.BoxCode + "-" + item.WarehouseCode, null, null, null, null, null, null, item.BoxCode, item.WarehouseCode);
                    }
                }
                View_TaskOrder();
            }
            catch (Exception ex)
            {
         
                LognetHelper.WriteLog("异常闪退:*-", ex);
            }
            finally
            {
                IsSubmitting=true;
            }
    
        }
        //箱盒视图
        private async void View_MaterialDto()
        {
            InPut_ViewService4.PageIndex = 1;
            InPut_ViewService4.PageSize = 100;
            InPut_ViewService4.BoxCode= InPut_BaseService7.BoxCode;
            Tuple<List<View_MaterialDto>, long?, long?>tuple= await  viewService.View_Material(InPut_ViewService4);
            if (tuple.Item1 != null)
            {
                View_MaterialDtos=tuple.Item1;
            }
        }
        //任务视图
        private async void View_TaskOrder()
        {
            InPut_ViewService5 inPut_ViewService5 = new InPut_ViewService5();
            inPut_ViewService5.PageIndex = 1;
            inPut_ViewService5.PageSize = 50;
            inPut_ViewService5.Type = "入库";
            inPut_ViewService5.State = "未下发";
            inPut_ViewService5.InlethouseCode=GlobalVariable.OutletCode;
            Tuple<List<View_TaskOrderDto>, long?, long?> tuple = await viewService.View_TaskOrder(inPut_ViewService5);
            if (tuple != null)
            {
                View_TaskOrderDtos = tuple.Item1;
            }
        }
        //出料视图
        private async void View_NeetOutMaterial()
        {
            InPut_ViewService10.PageIndex = 1;
            InPut_ViewService10.PageSize = 50;
            Tuple<List<View_NeetOutMaterialDto>, long?, long?> tuple = await viewService.View_NeetOutMaterial(InPut_ViewService10);
            if (tuple != null)
            {
                View_NeetOutMaterialDtos= tuple.Item1;
            }
        }
        //输送线滚动
        [RelayCommand]
        private async void movecontainer()
        {
            if(string.IsNullOrEmpty(BoxCode))
            {
                MessageBox.Info("请输入箱号");
                return;
            }
            await essService.moveContainer(BoxCode);
        }
        //缓存区图形
        private async Task GetInletCanves()
        {
          InlethouseModels=    await viewService.View_Inlethouse(GlobalVariable.InletCode);
        }
        //signalr
        public async Task GetHubConnectionAsync()
        {
            HubConnection hubConnection = await SingalrMethod.GetConnectionToWmsAsync();
            hubConnection.On<string>("CallByHub", async (string str) =>
            {
              await GetInletCanves();
                await baseService.CreateLog("收到", str, null, null, null, null, null, null, null, null);
            });
        }


        //主页设置
        private string title = "物料上下架";
        public string Title
        {
            get { return title; }
            set { title = value; RaisePropertyChanged(); }
        }
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }
        public async void OnNavigatedFrom(NavigationContext navigationContext)
        {
            
        }
        public async void OnNavigatedTo(NavigationContext navigationContext)
        {
            View_TaskOrder();
            InPut_ViewService4.PageIndex = 1;
            InPut_ViewService4.PageSize = 200;
            GetInletCanves();

        }
    }
}
